//
//  EventFlyersViewController.m
//  PartyAnimal
//
//  Created by Hilary Muludiang on 3/22/12.
//  Copyright 2012 Muludiang. All rights reserved.
//
// Source: https://developer.apple.com/library/ios/#samplecode/Scrolling/Introduction/Intro.html
// Page control: http://www.iosdevnotes.com/tag/uipagecontrol/

#import "EventFlyersViewController.h"
#import "iBacchanal.h"
#import "StackMob.h"
#import "UIImageView+AFNetworking.h"


@implementation EventFlyersViewController

@synthesize flyersScroller;
@synthesize pageControl;

const CGFloat kScrollObjWidth = 320.0;
const CGFloat KScrollObjHeight = 416.0;


-(void)scrollImages{
	
	NSArray *subviews = [flyersScroller subviews];
	
	//reposition image horizontally
	CGFloat curxLoc = 0;
	for (UIImageView *image in subviews){
		if ([image isKindOfClass:[UIImageView class]] && image.tag > 0){
			CGRect frame = image.frame;
			frame.origin = CGPointMake(curxLoc, 0);
			image.frame = frame;
			curxLoc += (kScrollObjWidth);
		}
	}
	// set content size so it is scrollable
	iBacchanal *bacchanal = [iBacchanal sharedUser];;
	[flyersScroller setContentSize:CGSizeMake((([bacchanal.eventFlyersArray count] ) * kScrollObjWidth), [flyersScroller bounds].size.height)];
	
}

-(IBAction)doneFlyers:(UIBarButtonItem *)sender{
	[self dismissModalViewControllerAnimated:YES];
}

-(IBAction)deleteEvent:(UIBarButtonItem *)sender{
	
	iBacchanal *bacchanal = [iBacchanal sharedUser];;
	
	//NSString *idValue = "@johndoe" // some primary key value for the object you want to update
	NSDictionary *args = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:1], @"hidden", nil];
	[[StackMob stackmob] put:@"events" withId:bacchanal.eventID andArguments:args andCallback:^(BOOL success, id result) {
		if (success) {
			// update successful, cast result to 
			// NSDictionary if necessary
			UIAlertView *submitAlert = [[UIAlertView alloc] initWithTitle:nil message:@"Event information successfully deleted." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
			[submitAlert show];
			
		} else {
			NSLog(@"%@", result);
			// update failed
		}
	}];
}


-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
	iBacchanal *bacchanal = [iBacchanal sharedUser];
	bacchanal.dataChanged = YES;
	[ self dismissModalViewControllerAnimated:YES];
	//[self.navigationController  popViewControllerAnimated:YES];	
	[alertView release];
}


- (void)scrollViewDidScroll:(UIScrollView *)sender {
    // Update the page when more than 50% of the previous/next page is visible
    CGFloat pageWidth = self.flyersScroller.frame.size.width;
    int page = floor((self.flyersScroller.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
    self.pageControl.currentPage = page;
}

- (IBAction)changePage {
    // update the scroll view to the appropriate page
    CGRect frame;
    frame.origin.x = self.flyersScroller.frame.size.width * self.pageControl.currentPage;
    frame.origin.y = 0;
    frame.size = self.flyersScroller.frame.size;
    [self.flyersScroller scrollRectToVisible:frame animated:YES];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    pageControlBeingUsed = NO;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    pageControlBeingUsed = NO;
}

// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
 self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
 if (self) {
 // Custom initialization.
 }
 return self;
 }
 */

/*
 // Implement loadView to create a view hierarchy programmatically, without using a nib.
 - (void)loadView {
 }
 */


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	iBacchanal *bacchanal = [iBacchanal sharedUser];;
	
	self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc]  initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneFlyers:)] autorelease];
	
	NSLog(@"%i", bacchanal.loggedIn);
	if(bacchanal.loggedIn && [bacchanal.currentUser isEqual: bacchanal.eventSubmitter])	
	self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"trash_can_30"] style:UIBarButtonItemStyleBordered target:self action:@selector(deleteEvent:)] autorelease];											  

	flyersScroller.indicatorStyle = UIScrollViewIndicatorStyleBlack;
	flyersScroller.showsHorizontalScrollIndicator = YES;
	flyersScroller.scrollEnabled = YES;
	flyersScroller.pagingEnabled = YES;
	flyersScroller.clipsToBounds = YES;
	
	//load the images
	self.navigationItem.title = bacchanal.eventName;
	
	NSLog(@"flyers: %i", [bacchanal.eventFlyersArray count]);
	pageControl.numberOfPages = [bacchanal.eventFlyersArray count];
	pageControl.hidesForSinglePage = YES;
	
	
	for (int i = 0; i < [bacchanal.eventFlyersArray count]; i++){
		NSURL *url = [NSURL URLWithString:[bacchanal.eventFlyersArray objectAtIndex:i] ];
		UIImageView *tempView = [[UIImageView alloc] init];
		[tempView setImageWithURL:url];
		//UIImageView *tempView = [[UIImageView alloc] initWithImage:[event.flyersArray objectAtIndex:i]];
		CGRect rect = tempView.frame;
		rect.size.height = KScrollObjHeight;
		rect.size.width = kScrollObjWidth;
		tempView.frame = rect;
		tempView.tag = (i+1);
		
		[flyersScroller addSubview:tempView];
		[tempView release];
	}
	
	pageControlBeingUsed = NO;
	
	[self scrollImages];
}

// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return YES; // (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {;
	[flyersScroller release];
    [super dealloc];
}


@end
